package com.link.base.base.autoconfig;

import java.util.Iterator;
import java.util.Map;

/**
 * @author 何启谦
 * @date 2019/9/10
 */
public class StringTool {

    /**
     * 替换所有匹配的字符串，无视表达式
     *
     * @param strData     源字符串
     * @param target      匹配替换的字符串
     * @param replacement 替换内容
     * @return 替换完成后的字符串
     */
    public static String replaceAll(String strData, String target, String replacement) {
        if (strData == null || strData == "") {
            return strData;
        }
        //定义转义字符数组
        char[] escapeChars = {'(', '[', '{', '/', '^', '-', '$', '¦', '}', ']', ')', '?', '*', '+', '.'};
        //处理转义字符
        StringBuilder sb = new StringBuilder();
        for (char targetChar : target.toCharArray()) {
            for (char escapeChar : escapeChars) {
                if (targetChar != escapeChar) {
                    continue;
                }
                //如果是转义字符，则前面加上"\"来去掉转义
                sb.append("\\");
                break;
            }
            sb.append(targetChar);
        }
        return strData.replaceAll(sb.toString(), replacement);
    }

    /**
     * 替换所有匹配的字符串，无视表达式
     *
     * @param strData   源字符串
     * @param targetMap {key: 匹配替换的字符串; value: 替换内容}
     * @return 替换完成后的字符串
     */
    public static String replaceAll(String strData, Map<String, String> targetMap) {
        if (strData == null || targetMap == null || targetMap.size() == 0) {
            return strData;
        }
        Iterator<Map.Entry<String, String>> entries = targetMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            String target = entry.getKey();
            String replacement = entry.getValue();
            strData = replaceAll(strData, target, replacement);
        }
        return strData;
    }
}
